import request from "./request";
import { message } from "antd";
let onlyOne = false;
export const getChatDataFetch = async (payload: {message: string,conversationId:number},returnData:()=>any) => {
    if (onlyOne) return;
    onlyOne = true;
    const response = await fetch('/api/chat', {
        method: "post",
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${localStorage.getItem("token")}`
        },
        body: JSON.stringify(payload),
    })
    const reader = response.body.getReader();
    while(true){
        const { done, value } = await reader.read();
        if (done) {
          returnData("", done, 'done');
          onlyOne = false;
          break;
        }
        let newText = new TextDecoder("utf-8").decode(value);
        returnData(newText, false, "text");
    }
};


// 获取全部历史记录
export const getChatHistoryFetch = async (payload:{conversationId:number}) => {
    return new Promise((resolve, reject) => {
        request.get({
            url: '/api/chat',
            params: payload
        }).then(res => {
            resolve(res);
        }).catch(err => {
            message.warning({
              content: '获取历史记录失败',
            });
            reject(err);
        });
    });
}

// 删除历史记录
export const deleteChatHistoryFetch = async (id: string) => {
    return request.delete({
        url: `/api/chat`,
        params: {
            id
        }
    });
}

// 获取用户的对话列表
export const getConversationListFetch = async () => {
    return request.get({
        url: '/api/chat/conversation',
    });
}

// 删除对话
export const deleteConversationFetch = async (payload:{conversationId:number}) => {
    return request.delete({
        url: '/api/chat/conversation',
        params: payload
    });
}

// 创建图像
export const createImageFetch = async (payload:{message:string,conversationId:number}) => {
    return request.post({
        url: '/api/image',
        data: payload
    });
}

// 获取图像任务状态
export const getImageTaskFetch = async (payload:{taskId:string,conversationId:number}) => {
    return request.get({
        url: '/api/image',
        params: payload
    });
}

